//
//  PHAsset+Extension.swift
//  Library_y
//
//  Created by JC on 2023/6/6.
//

import Foundation
import Photos
import HXPHPicker

public typealias BlockURL = (_ url: URL?) -> Void
public extension PHAsset {
    
    // 获取资源URL
    func getUrl(_ block: BlockURL? = nil) {
        let photoAsset = PhotoAsset(asset: self)
        if self.url == nil {
            // iCloud去下载
            if photoAsset.mediaType == .photo {
                let options = PHImageRequestOptions()
                // deliveryMode 控制获取的图像的质量
                options.deliveryMode = .highQualityFormat
                // networkAccessAllowed是否允许网络请求,可以从icloud获取更加清晰的图像
                options.isNetworkAccessAllowed = true
                options.progressHandler = { (progress, error, stop, info) in
                    // 可以控制进度条
                    if progress < 1 {
                        Log_y.print_("正在同步iCloud：\(progress * 100)%")
                    }
                }
                PHImageManager.default().requestImage(for: self, targetSize: PHImageManagerMaximumSize,contentMode: PHImageContentMode.aspectFill, options: options, resultHandler: { (img, info) in
                    var url: URL?
                    if let originalFilename = self.originalFilename,
                       let u = img?.toData()?.write(withName: originalFilename) {
                        Log_y.print_("iCloud图片同步完成：\(u)")
                        url = u
                    }
                    block?(url)
                })
            } else if self.mediaType == .video {
                photoAsset.requestAVAsset { _, _ in
                    Log_y.print_("正在同步iCloud...")
                } progressHandler: { _, progress in
                    Log_y.print_("正在同步iCloud：\(progress * 100)%")
                } success: { photoAsset, avAsset, _ in
                    var url: URL?
                    if let videoAsset = avAsset as? AVURLAsset {
                        Log_y.print_("iCloud视频同步完成：\(videoAsset.url)")
                        url = videoAsset.url
                    }
                    block?(url)
                } failure: { _, _, _ in
                    Log_y.print_("iCloud同步失败")
                    block?(nil)
                }
            } else {
                
            }
        } else {
            block?(self.url)
        }
    }
    
    var fileSize: Float {
        get {
            var mediaSize: Float = 0
            let resource = PHAssetResource.assetResources(for: self)
            if let imageSizeByte = resource.first?.value(forKey: "fileSize") as? Float {
                mediaSize = imageSizeByte
            }
            return mediaSize
        }
    }
    
    var url: URL? {
        var pathRrl: URL?
        let re = PHAssetResource.assetResources(for: self).last
        if let url = re?.value(forKey: "privateFileURL") as? URL {
            let urlStr = url.absoluteString.dropFirst(8)
            pathRrl = URL(string: String(urlStr))
        }
        return pathRrl
    }
    
    var originalFilename: String? {
        var fname: String?
        let resources = PHAssetResource.assetResources(for: self)
        if let resource = resources.first {
            fname = resource.originalFilename
        }
        return fname
    }
}
